#!/usr/bin/env node

const Koa = require('koa'),
      Router = require('koa-router'),
      router = new Router(),
      //router = require('koa-router')(),
      users = require('../models/users'),
      jwt   = require('jsonwebtoken'),
      {JWT_KEY} = require('../lib/constant'),
      _   = require('lodash'),
      log = console.log;

//ctx 上下文； next 调用后面的中间件 

router.prefix('/api/users');

router.post('/login',async(ctx,next) => { 
  let {email,password} = ctx.request.body;

  let res = await users.login(email,password);

  log(res.code);
  if(res.code === 0){
    // generate token
    // send token to client
    // res.data = token
    
    res.data = await jwt.sign(_.toPlainObject(res.data),JWT_KEY);
  }
  ctx.body = res;     
});

module.exports = router;
